// 检查是否在客户端环境
const isClient = () => {
  return typeof window !== 'undefined' && typeof document !== 'undefined'
}

export interface PdfExportOptions {
  filename?: string
  quality?: number
  scale?: number
  backgroundColor?: string
  margin?: {
    top: number
    right: number
    bottom: number
    left: number
  }
}

export const usePdfExport = () => {
  /**
   * 导出元素为PDF
   * @param element 要导出的DOM元素
   * @param options 导出选项
   */
  const exportToPdf = async (
    element: HTMLElement,
    options: PdfExportOptions = {}
  ): Promise<void> => {
    try {
      const {
        filename = 'resume.pdf',
        quality = 0.98,
        scale = 2,
        backgroundColor = '#ffffff',
        margin = { top: 10, right: 10, bottom: 10, left: 10 }
      } = options

      // 显示加载状态
      console.log('开始生成PDF...')

      // 检查客户端环境
      if (!isClient()) {
        throw new Error('PDF导出功能仅在客户端可用')
      }

      // 动态导入PDF库
      const [html2canvasModule, jsPDFModule] = await Promise.all([
        import('html2canvas'),
        import('jspdf')
      ])
      
      const html2canvas = html2canvasModule.default
      const jsPDF = jsPDFModule.default

      // 使用html2canvas将元素转换为canvas
      const canvas = await html2canvas(element, {
        scale,
        useCORS: true,
        allowTaint: true,
        backgroundColor,
        logging: false,
        width: element.scrollWidth,
        height: element.scrollHeight
      })

      // 计算PDF尺寸
      const imgWidth = canvas.width
      const imgHeight = canvas.height
      const pdfWidth = 210 // A4宽度 (mm)
      const pdfHeight = 297 // A4高度 (mm)
      
      // 计算缩放比例，确保内容适合A4纸张
      const ratio = Math.min(
        (pdfWidth - margin.left - margin.right) / imgWidth,
        (pdfHeight - margin.top - margin.bottom) / imgHeight
      )
      
      const scaledWidth = imgWidth * ratio
      const scaledHeight = imgHeight * ratio

      // 创建PDF文档
      const pdf = new jsPDF({
        orientation: scaledHeight > pdfHeight ? 'landscape' : 'portrait',
        unit: 'mm',
        format: 'a4'
      })

      // 将canvas转换为图片
      const imgData = canvas.toDataURL('image/png', quality)

      // 添加图片到PDF
      pdf.addImage(
        imgData,
        'PNG',
        margin.left,
        margin.top,
        scaledWidth,
        scaledHeight
      )

      // 保存PDF
      pdf.save(filename)
      
      console.log('PDF导出成功')
    } catch (error) {
      console.error('PDF导出失败:', error)
      throw new Error('PDF导出失败，请重试')
    }
  }

  /**
   * 导出简历为PDF
   * @param resumeData 简历数据
   * @param options 导出选项
   */
  const exportResumeToPdf = async (
    resumeData: any,
    options: PdfExportOptions = {}
  ): Promise<void> => {
    try {
      const {
        filename = `${resumeData.name || '简历'}.pdf`,
        quality = 0.98,
        scale = 2,
        backgroundColor = '#ffffff'
      } = options

      // 创建临时容器
      const tempContainer = document.createElement('div')
      tempContainer.style.position = 'absolute'
      tempContainer.style.left = '-9999px'
      tempContainer.style.top = '-9999px'
      tempContainer.style.width = '800px'
      tempContainer.style.backgroundColor = backgroundColor
      tempContainer.style.padding = '40px'
      tempContainer.style.fontFamily = 'Microsoft YaHei, sans-serif'
      tempContainer.style.lineHeight = '1.6'
      tempContainer.style.color = '#333'

      // 生成简历HTML内容
      const resumeHtml = generateResumeHtml(resumeData)
      tempContainer.innerHTML = resumeHtml

      // 添加到DOM
      document.body.appendChild(tempContainer)

      // 等待字体和样式加载
      await new Promise(resolve => setTimeout(resolve, 100))

      // 导出为PDF
      await exportToPdf(tempContainer, {
        ...options,
        filename
      })

      // 清理临时元素
      document.body.removeChild(tempContainer)
    } catch (error) {
      console.error('简历PDF导出失败:', error)
      throw error
    }
  }

  /**
   * 生成简历HTML内容
   * @param resumeData 简历数据
   */
  const generateResumeHtml = (resumeData: any): string => {
    const { name, phone, email, hometown, jobIntention, education, workExperience, projects, skills, selfEvaluation } = resumeData

    return `
      <div style="max-width: 800px; margin: 0 auto; background: white;">
        <!-- 简历头部 -->
        <div style="text-align: center; margin-bottom: 30px; padding-bottom: 20px; border-bottom: 2px solid #1890ff;">
          <h1 style="font-size: 32px; font-weight: bold; color: #333; margin: 0 0 15px 0;">${name || '姓名'}</h1>
          <div style="display: flex; justify-content: center; flex-wrap: wrap; gap: 20px; font-size: 14px; color: #666;">
            ${phone ? `<span>电话: ${phone}</span>` : ''}
            ${email ? `<span>邮箱: ${email}</span>` : ''}
            ${hometown ? `<span>籍贯: ${hometown}</span>` : ''}
            ${jobIntention ? `<span>求职意向: ${jobIntention}</span>` : ''}
          </div>
        </div>

        <!-- 专业技能 -->
        ${skills && skills.length > 0 ? `
          <div style="margin-bottom: 25px;">
            <h2 style="font-size: 18px; font-weight: bold; color: #333; margin-bottom: 15px; padding-bottom: 8px; border-bottom: 1px solid #e8e8e8;">专业技能</h2>
            ${skills.map((skill: any) => `
              <p style="margin: 0 0 10px 0; color: #666; line-height: 1.6;">${skill.description}</p>
            `).join('')}
          </div>
        ` : ''}

        <!-- 工作经历 -->
        ${workExperience && workExperience.length > 0 ? `
          <div style="margin-bottom: 25px;">
            <h2 style="font-size: 18px; font-weight: bold; color: #333; margin-bottom: 15px; padding-bottom: 8px; border-bottom: 1px solid #e8e8e8;">工作经历</h2>
            ${workExperience.map((work: any) => `
              <div style="margin-bottom: 20px;">
                <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 8px;">
                  <h3 style="font-size: 16px; font-weight: 600; color: #333; margin: 0;">${work.position}</h3>
                  <span style="color: #1890ff; font-weight: 500;">${work.company}</span>
                  <span style="color: #999; font-size: 14px; margin-left: auto;">${work.startDate} - ${work.endDate}</span>
                </div>
                <div style="color: #666; line-height: 1.6;">
                  <p style="margin: 0;">${work.description}</p>
                </div>
              </div>
            `).join('')}
          </div>
        ` : ''}

        <!-- 教育背景 -->
        ${education && education.length > 0 ? `
          <div style="margin-bottom: 25px;">
            <h2 style="font-size: 18px; font-weight: bold; color: #333; margin-bottom: 15px; padding-bottom: 8px; border-bottom: 1px solid #e8e8e8;">教育背景</h2>
            ${education.map((edu: any) => `
              <div style="margin-bottom: 15px;">
                <div style="display: flex; align-items: center; gap: 12px;">
                  <h3 style="font-size: 16px; font-weight: 600; color: #333; margin: 0;">${edu.major} - ${edu.degree}</h3>
                  <span style="color: #1890ff; font-weight: 500;">${edu.school}</span>
                  <span style="color: #999; font-size: 14px; margin-left: auto;">${edu.startDate} - ${edu.endDate}</span>
                </div>
              </div>
            `).join('')}
          </div>
        ` : ''}

        <!-- 项目经验 -->
        ${projects && projects.length > 0 ? `
          <div style="margin-bottom: 25px;">
            <h2 style="font-size: 18px; font-weight: bold; color: #333; margin-bottom: 15px; padding-bottom: 8px; border-bottom: 1px solid #e8e8e8;">项目经验</h2>
            ${projects.map((project: any) => `
              <div style="margin-bottom: 20px;">
                <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 8px;">
                  <h3 style="font-size: 16px; font-weight: 600; color: #333; margin: 0;">${project.name}</h3>
                  <span style="color: #1890ff; font-weight: 500;">${project.role}</span>
                  <span style="color: #999; font-size: 14px; margin-left: auto;">${project.duration}</span>
                </div>
                <div style="color: #666; line-height: 1.6;">
                  <p style="margin: 0;">${project.description}</p>
                </div>
              </div>
            `).join('')}
          </div>
        ` : ''}

        <!-- 自我评价 -->
        ${selfEvaluation ? `
          <div style="margin-bottom: 25px;">
            <h2 style="font-size: 18px; font-weight: bold; color: #333; margin-bottom: 15px; padding-bottom: 8px; border-bottom: 1px solid #e8e8e8;">自我评价</h2>
            <div style="color: #666; line-height: 1.6;">
              <p style="margin: 0;">${selfEvaluation}</p>
            </div>
          </div>
        ` : ''}
      </div>
    `
  }

  return {
    exportToPdf,
    exportResumeToPdf,
    generateResumeHtml
  }
}
